<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="课程标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入课程标题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="课程评分" prop="score">
        <el-input
          v-model="queryParams.score"
          placeholder="请输入课程评分"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="发布时间">
        <el-date-picker
          v-model="daterangeCreateTime"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['course:courses:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['course:courses:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['course:courses:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['course:courses:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 课程列表表格 -->
    <el-table v-loading="loading" :data="coursesList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" />
      <el-table-column label="作者名" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.users.nickname }}</span>
        </template>
      </el-table-column>
      <el-table-column label="课程标题" align="center" prop="title" />
      <el-table-column label="课程简介" align="center" prop="description" />
      <el-table-column label="课程评分" align="center" prop="score" />
      <el-table-column label="参与人数" align="center" prop="participantCount" />
      <el-table-column label="发布时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="课程总时长" align="center" prop="totalDuration" />
      <el-table-column label="视频总节数" align="center" prop="totalVideos" />
      <!-- 状态列：直接根据返回的 status 显示，简洁清晰 -->
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <span :style="{ color: scope.row.status === 1 ? 'red' : 'green' }">
            {{ scope.row.status === 0 ? '正常' : '停用' }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['course:courses:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['course:courses:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改课程弹窗 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <!-- 新增时显示作者ID输入框，修改时显示作者名下拉框 -->
        <template v-if="form.id">
          <el-form-item label="作者名" prop="userId">
            <el-select v-model="form.userId" placeholder="请选择作者" clearable>
              <el-option
                v-for="author in authors"
                :key="author.id"
                :label="author.nickname"
                :value="author.id"
              />
            </el-select>
          </el-form-item>
        </template>
        <template v-else>
          <el-form-item label="作者ID" prop="userId">
            <el-input v-model="form.userId" placeholder="请输入作者ID" />
          </el-form-item>
        </template>

        <el-form-item label="课程标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入课程标题" />
        </el-form-item>
        <el-form-item label="课程简介" prop="description">
          <el-input v-model="form.description" placeholder="请输入课程简介" />
        </el-form-item>
        <el-form-item label="课程评分" prop="score">
          <el-input v-model="form.score" placeholder="请输入课程评分" />
        </el-form-item>

        <!-- 参与人数：仅修改时显示且禁用，新增不显示 -->
        <template v-if="!isAdd">
          <el-form-item label="参与人数" prop="participantCount">
            <el-input
              v-model="form.participantCount"
              placeholder="请输入参与人数"
              disabled
            />
          </el-form-item>
        </template>

        <!-- 状态：下拉框，0→正常，1→停用 -->
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option label="正常" :value="0"></el-option>
            <el-option label="停用" :value="1"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCourses, getCourses, delCourses, addCourses, updateCourses } from "@/api/course/courses";
import request from '@/utils/request';
import Pagination from '@/components/Pagination';
import RightToolbar from '@/components/RightToolbar';

export default {
  name: "Courses",
  components: { Pagination, RightToolbar },
  data() {
    return {
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      coursesList: [],
      authors: [],
      title: "",
      open: false,
      daterangeCreateTime: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: null,
        score: null,
        createTime: null,
      },
      form: {},
      isAdd: false,
      rules: {
        userId: [
          { required: true, message: "作者信息不能为空", trigger: "blur" }
        ],
        title: [
          { required: true, message: "课程标题不能为空", trigger: "blur" }
        ],
        score: [
          { required: true, message: "课程评分不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "状态不能为空", trigger: "change" }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getAuthors();
  },
  methods: {
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (this.daterangeCreateTime) {
        this.queryParams.params["beginCreateTime"] = this.daterangeCreateTime[0];
        this.queryParams.params["endCreateTime"] = this.daterangeCreateTime[1];
      }
      listCourses(this.queryParams).then((response) => {
        this.coursesList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getAuthors() {
      request({
        url: "/course/courseUser/list",
        method: "get",
      })
        .then((response) => {
          this.authors = response.rows || [];
        })
        .catch((err) => {
          console.error("获取作者列表失败：", err);
          this.$message.error("获取作者列表失败，请稍后重试");
        });
    },
    cancel() {
      this.open = false;
      this.reset();
    },
    reset() {
      this.form = {
        id: null,
        userId: null,
        title: null,
        description: null,
        score: null,
        participantCount: null,
        createTime: null,
        totalDuration: null,
        totalVideos: null,
        status: 0, // 默认正常
      };
      this.resetForm("form");
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.daterangeCreateTime = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加课程";
      this.isAdd = true;
    },
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getCourses(id).then((response) => {
        // 直接赋值，接口返回的 status 已是数字，无需额外转换
        this.form = { ...response.data };
        this.open = true;
        this.title = "修改课程";
        this.isAdd = false;
      });
    },
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          const requestFn = this.isAdd ? addCourses : updateCourses;
          requestFn(this.form)
            .then((response) => {
              this.$modal.msgSuccess(this.isAdd ? "新增成功" : "修改成功");
              this.open = false;
              this.getList();
            })
            .catch((err) => {
              console.error("提交失败:", err);
              this.$modal.msgError("操作失败，请重试");
            });
        }
      });
    },
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm(`是否确认删除课程ID为"${ids}"的数据？`).then(() => {
        return delCourses(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    handleExport() {
      this.download(
        "course/courses/export",
        { ...this.queryParams },
        `courses_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>

<style scoped>
/* 样式可根据实际需求自定义 */
</style>
